package main.cn.web;

import main.cn.pojo.Pet;
import main.cn.service.PetService;
import main.cn.service.impl.PetServiceImpl;
import main.cn.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet(urlPatterns = "/client/petServlet")
public class PetServlet extends BaseServlet{

    private PetService petService = new PetServiceImpl();

    protected void add(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        Pet _pet = WebUtils.copyParamToBean(req.getParameterMap(), new Pet());
        petService.addPet(_pet);
        resp.sendRedirect(req.getContextPath() + "/client/petServlet?action=list");
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("id"));
        int pid = WebUtils.parseInt(req.getParameter("id"),0);
//        2、调用petService.deletePetById();删除
        petService.deletePetById(pid);
        resp.sendRedirect(req.getContextPath() + "/client/petServlet?action=list");
    }


    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Pet _pet = WebUtils.copyParamToBean(req.getParameterMap(), new Pet());
        petService.updatePet(_pet);
        resp.sendRedirect(req.getContextPath() + "/client/petServlet?action=list");
    }


    protected void getPet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pid = WebUtils.parseInt(req.getParameter("id"),0);
        Pet _pet = petService.queryPetById(pid);
        req.setAttribute("pets",_pet);
        req.getRequestDispatcher("/page/edit/pet_edit.jsp").forward(req,resp);
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        List<Pet> pets = petService.queryPets();

        req.setAttribute("pets",pets);

        req.getRequestDispatcher("/page/client/index.jsp").forward(req,resp);
    }




}
